"""
Created on Mar 1, 2020
Pytorch Implementation of LightGCN in
Xiangnan He et al. LightGCN: Simplifying and Powering Graph Convolution Network for Recommendation

@author: Jianbai Ye (gusye@mail.ustc.edu.cn)

Define models here
"""
import dataloader
import world
import torch
from dataloader import BasicDataset
from torch import nn
import numpy as np


class BasicModel(nn.Module):    
    def __init__(self):
        super(BasicModel, self).__init__()
    
    def getUsersRating(self, users):
        raise NotImplementedError
    
class PairWiseModel(BasicModel):
    def __init__(self):
        super(PairWiseModel, self).__init__()
    #计算bpr损失
    def bpr_loss(self, users, pos, neg):
        """
        Parameters:
            users: users list 
            pos: positive items for corresponding users
            neg: negative items for corresponding users
        Return:
            (log-loss, l2-loss)
        """
        raise NotImplementedError
    
class PureMF(BasicModel):
    def __init__(self, 
                 config:dict, 
                 dataset:BasicDataset):
        super(PureMF, self).__init__()
        self.num_users  = dataset.n_users
        self.num_items  = dataset.m_items
        self.latent_dim = config['latent_dim_rec']
        self.f = nn.Sigmoid()
        self.__init_weight()

    #初始化嵌入向量
    def __init_weight(self):
        self.embedding_user = torch.nn.Embedding(
            num_embeddings=self.num_users, embedding_dim=self.latent_dim)
        self.embedding_item = torch.nn.Embedding(
            num_embeddings=self.num_items, embedding_dim=self.latent_dim)
        print("using Normal distribution N(0,1) initialization for PureMF")
    #获取用户评分 输入users是一个一维数组[] 输出一个一维向量包含一个用户的所有评分
    def getUsersRating(self, users):
        users = users.long()

        users_emb = self.embedding_user(users)
        items_emb = self.embedding_item.weight
        scores = torch.matmul(users_emb, items_emb.t())
        return self.f(scores)
    #计算bpr损失
    #users[2048] pos[2048] neg[2048]
    def bpr_loss(self, users, pos, neg):
        #emb嵌入向量为[2048,64]
        users_emb = self.embedding_user(users.long())
        pos_emb   = self.embedding_item(pos.long())
        neg_emb   = self.embedding_item(neg.long())
        #所有列相加 从[n,m]-所有列相加->[n,1]
        pos_scores= torch.sum(users_emb*pos_emb, dim=1)
        neg_scores= torch.sum(users_emb*neg_emb, dim=1)
        #Softplus函数的形式为：f(x) = ln(1 + e^x)。它是一个平滑的替代函数，用于将负值转换为正值。
        #torch.mean(): 这个函数是用来计算张量（即多维数组）中所有元素的平均值。是一个标量
        loss = torch.mean(nn.functional.softplus(neg_scores - pos_scores))
        #计算正则化损失users_emb.norm(2): 这部分计算users_emb张量中每个元素的L2范数。L2范数计算的是元素平方和的平方根，通常用于衡量向量的大小。
        reg_loss = (1/2)*(users_emb.norm(2).pow(2) + 
                          pos_emb.norm(2).pow(2) + 
                          neg_emb.norm(2).pow(2))/float(len(users))
        return loss, reg_loss
        
    def forward(self, users, items):
        users = users.long()
        items = items.long()
        users_emb = self.embedding_user(users)
        items_emb = self.embedding_item(items)
        scores = torch.sum(users_emb*items_emb, dim=1)
        return self.f(scores)

class LightGCN(BasicModel):
    def __init__(self, 
                 config:dict, 
                 dataset:BasicDataset):
        super(LightGCN, self).__init__()
        self.config = config
        self.dataset : dataloader.BasicDataset = dataset
        self.__init_weight()

    def __init_weight(self):
        self.num_users  = self.dataset.n_users
        self.num_items  = self.dataset.m_items
        self.latent_dim = self.config['latent_dim_rec']
        self.n_layers = self.config['lightGCN_n_layers']
        self.keep_prob = self.config['keep_prob']
        self.A_split = self.config['A_split']
        self.embedding_user = torch.nn.Embedding(
            num_embeddings=self.num_users, embedding_dim=self.latent_dim)
        self.embedding_item = torch.nn.Embedding(
            num_embeddings=self.num_items, embedding_dim=self.latent_dim)
        if self.config['pretrain'] == 0:
            #nn.init.xavier_uniform_(self.embedding_user.weight, gain=1)
            #nn.init.xavier_uniform_(self.embedding_item.weight, gain=1)
            #print('use xavier initilizer')
            #random normal init seems to be a better choice when lightGCN actually don't use any non-linear activation function
            #如果没有预训练的emb嵌入向量则对权重进行正态初始化
            nn.init.normal_(self.embedding_user.weight, std=0.1)
            nn.init.normal_(self.embedding_item.weight, std=0.1)
            world.cprint('use NORMAL distribution initilizer')
        else:
            self.embedding_user.weight.data.copy_(torch.from_numpy(self.config['user_emb']))
            self.embedding_item.weight.data.copy_(torch.from_numpy(self.config['item_emb']))
            print('use pretarined data')
        self.f = nn.Sigmoid()
        self.Graph = self.dataset.getSparseGraph()
        print(f"lgn is already to go(dropout:{self.config['dropout']})")

        # print("save_txt")
    def __dropout_x(self, x, keep_prob):
        size = x.size()
        index = x.indices().t()
        values = x.values()
        random_index = torch.rand(len(values)) + keep_prob
        random_index = random_index.int().bool()
        index = index[random_index]
        values = values[random_index]/keep_prob
        g = torch.sparse.FloatTensor(index.t(), values, size)
        return g
    
    def __dropout(self, keep_prob):
        if self.A_split:
            graph = []
            for g in self.Graph:
                graph.append(self.__dropout_x(g, keep_prob))
        else:
            graph = self.__dropout_x(self.Graph, keep_prob)
        return graph

    # 返回用户和商品的特征矩阵
    def computer(self):
        """
        propagate methods for lightGCN
        """
        #users_emb  :[user_len,64]
        users_emb = self.embedding_user.weight
        #items_emb  :[item_len,64]
        items_emb = self.embedding_item.weight
        #列向量相等 没有添加维度参数默认从dim=0拼接 即all_emb ： [user_len+item_len,64]
        all_emb = torch.cat([users_emb, items_emb])
        #   torch.split(all_emb , [self.num_users, self.num_items])
        embs = [all_emb]
        #随机丢弃
        if self.config['dropout']:
            if self.training:
                print("droping")
                g_droped = self.__dropout(self.keep_prob)
            else:
                g_droped = self.Graph        
        else:
            g_droped = self.Graph    
        #self.n_layers为3层
        for layer in range(self.n_layers):
            if self.A_split:
                temp_emb = []
                #g_droped图交互矩阵(self.n_users + self.m_items, self.n_users + self.m_items)
                #len(g_droped)只返回第一个维度的大小
                for f in range(len(g_droped)):
                    #g_droped[f]取第f行 = [self.n_users + self.m_items]
                    #all_emb = [self.n_users + self.m_items，64]
                    #为1的地方才有嵌入值 为0的地方嵌入值为0
                    temp_emb.append(torch.sparse.mm(g_droped[f], all_emb))
                side_emb = torch.cat(temp_emb, dim=0)
                all_emb = side_emb
            else:
                #特征计算 每次循环all_emb通过图卷积更新参数
                all_emb = torch.sparse.mm(g_droped, all_emb)
            #将每次图卷积的参数放入embs列表中
            embs.append(all_emb)
        #embs在stack之前是一个列表里面的元素为tensor
        #embs:[self.n_users + self.m_items , self.n_layers , 64]
        embs = torch.stack(embs, dim=1)
        #print(embs.size())
        #按下标为1的维度进行求平均
        light_out = torch.mean(embs, dim=1)
        #把light_out[70839,64]分成两个张量
        #users [29858,64]  items [40981,64]
        users, items = torch.split(light_out, [self.num_users, self.num_items])
        #返回用户和商品的特征矩阵
        return users, items

    #获取用户预测评分 输出一批用户的评分向量 返回结果rating[100,item_len]
    #users = [100]
    def getUsersRating(self, users):
        #获取用户和商品的嵌入向量
        all_users, all_items = self.computer()
        #users_emb[100,64]
        users_emb = all_users[users.long()]
        #items_emb[item_len,64]
        items_emb = all_items
        #rating[100,item_len]
        rating = self.f(torch.matmul(users_emb, items_emb.t()))
        return rating

    #获取嵌入向量users_emb, pos_emb, neg_emb是图卷积后的向量
    #users_emb_ego, pos_emb_ego, neg_emb_ego是原始嵌入向量
    def getEmbedding(self, users, pos_items, neg_items):
        #获取用户和商品特征向量
        all_users, all_items = self.computer()
        #users, pos_items, neg_items都为一维tensor 长为[2048]
        users_emb = all_users[users]
        pos_emb = all_items[pos_items]
        neg_emb = all_items[neg_items]
        users_emb_ego = self.embedding_user(users)
        pos_emb_ego = self.embedding_item(pos_items)
        neg_emb_ego = self.embedding_item(neg_items)
        return users_emb, pos_emb, neg_emb, users_emb_ego, pos_emb_ego, neg_emb_ego
    
    def bpr_loss(self, users, pos, neg):
        (users_emb, pos_emb, neg_emb, 
        userEmb0,  posEmb0, negEmb0) = self.getEmbedding(users.long(), pos.long(), neg.long())
        reg_loss = (1/2)*(userEmb0.norm(2).pow(2) + 
                         posEmb0.norm(2).pow(2)  +
                         negEmb0.norm(2).pow(2))/float(len(users))
        pos_scores = torch.mul(users_emb, pos_emb)
        pos_scores = torch.sum(pos_scores, dim=1)
        neg_scores = torch.mul(users_emb, neg_emb)
        neg_scores = torch.sum(neg_scores, dim=1)
        
        loss = torch.mean(torch.nn.functional.softplus(neg_scores - pos_scores))
        
        return loss, reg_loss
       
    def forward(self, users, items):
        # compute embedding
        #self.computer()获得图卷积后的商品和用户嵌入向量
        all_users, all_items = self.computer()
        # print('forward')
        #all_users, all_items = self.computer()
        users_emb = all_users[users]
        items_emb = all_items[items]
        #获得用户的评分矩阵
        inner_pro = torch.mul(users_emb, items_emb)
        gamma     = torch.sum(inner_pro, dim=1)
        return gamma
